package cz.khfotbal.beans;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cz.khfotbal.dao.DownloadDao;
import cz.khfotbal.domain.Competion;
import cz.khfotbal.domain.Match;
import cz.khfotbal.domain.Season;
import cz.khfotbal.domain.Team;
import cz.khfotbal.service.CompetionService;
import cz.khfotbal.service.MatchService;
import cz.khfotbal.service.SeasonService;
import cz.khfotbal.service.TeamService;
import cz.khfotbal.utils.KHFotbalUtils;

@Component
@Scope(value = "session")
public class ExportTablesBean {

	@Autowired
	private TeamService teamService;
	@Autowired
	private SeasonService seasonService;
	@Autowired
	private CompetionService competionService;
	@Autowired
	private MatchService matchService;
	@Autowired
	DownloadDao downloadDao;

//	private static final String FILE_DESTINATION = "D://Data//khfotbal//";
	private static String FILE_DESTINATION = "";

	
	private Season selectedSeason;
	private Competion selectedCompetion;
	private List<Team> teamList = new ArrayList<Team>();
	private List<Match> matchFilteredList = new ArrayList<Match>();
	private String filename;

	public Team getTeamFromListById(int id) {
		for (Team t : teamList) {
			if (t.getId() == id)
				return t;
		}
		return null;
	}

	public void exportTables() {
		Date dateNow = new Date();
		SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat(
				"ssmmHHddMMyyyy");
		StringBuilder dayInString = new StringBuilder(
				dateformatYYYYMMDD.format(dateNow));
		filename = dayInString.toString() + ".TXT";

		ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
				.getExternalContext().getContext();
		FILE_DESTINATION = ctx.getRealPath("/");

		// SimpleDateFormat dateformatYYYYMMDDPopis = new
		// SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		// StringBuilder dayInStringPopis = new StringBuilder(
		// dateformatYYYYMMDDPopis.format( dateNow ) );
		//
		// DownloadFile downloadFile = new DownloadFile();
		// downloadFile.setDescription(dayInStringPopis.toString());
		// downloadFile.setFilename(filename);
		// downloadFile.setCategory("export");
		// downloadDao.saveFile(downloadFile);

		List<Season> seasons = seasonService.getAllSeasons();
		for (Season season : seasons) {
			selectedSeason = season;
		}

		List<Competion> competions = competionService.getAllCompetions();
		for (Competion competion : competions) {
			selectedCompetion = competion;

			matchFilteredList = matchService.getMatchesBySeasonAndCompetion(
					selectedSeason, selectedCompetion);

			teamList = teamService.getTeamsBySeasonAndCompetion(selectedSeason,
					selectedCompetion);
			for (Match match : matchFilteredList) {
				if ((match.getHomeTeamScore() != null && match
						.getAwayTeamScore() != null)
						&& (KHFotbalUtils.isInteger(match.getHomeTeamScore()) && (KHFotbalUtils
								.isInteger(match.getAwayTeamScore())))) {
					getTeamFromListById(match.getHomeTeam().getId())
							.getResultData().setMatches(
									getTeamFromListById(
											match.getHomeTeam().getId())
											.getResultData().getMatches() + 1);
					getTeamFromListById(match.getAwayTeam().getId())
							.getResultData().setMatches(
									getTeamFromListById(
											match.getAwayTeam().getId())
											.getResultData().getMatches() + 1);
					getTeamFromListById(match.getHomeTeam().getId())
							.getResultData().setScoredGoals(
									getTeamFromListById(
											match.getHomeTeam().getId())
											.getResultData().getScoredGoals()
											+ Integer.valueOf(match
													.getHomeTeamScore()));
					getTeamFromListById(match.getAwayTeam().getId())
							.getResultData().setScoredGoals(
									getTeamFromListById(
											match.getAwayTeam().getId())
											.getResultData().getScoredGoals()
											+ Integer.valueOf(match
													.getAwayTeamScore()));
					getTeamFromListById(match.getHomeTeam().getId())
							.getResultData().setCollectedGoals(
									getTeamFromListById(
											match.getHomeTeam().getId())
											.getResultData()
											.getCollectedGoals()
											+ Integer.valueOf(match
													.getAwayTeamScore()));
					getTeamFromListById(match.getAwayTeam().getId())
							.getResultData().setCollectedGoals(
									getTeamFromListById(
											match.getAwayTeam().getId())
											.getResultData()
											.getCollectedGoals()
											+ Integer.valueOf(match
													.getHomeTeamScore()));
					if (Integer.valueOf(match.getHomeTeamScore()) > Integer
							.valueOf(match.getAwayTeamScore())) {
						getTeamFromListById(match.getHomeTeam().getId())
								.getResultData()
								.setPoints(
										getTeamFromListById(
												match.getHomeTeam().getId())
												.getResultData().getPoints() + 3);
						getTeamFromListById(match.getHomeTeam().getId())
								.getResultData().setWins(
										getTeamFromListById(
												match.getHomeTeam().getId())
												.getResultData().getWins() + 1);
						getTeamFromListById(match.getAwayTeam().getId())
								.getResultData().setLoss(
										getTeamFromListById(
												match.getAwayTeam().getId())
												.getResultData().getLoss() + 1);
					}
					if (Integer.valueOf(match.getHomeTeamScore()) < Integer
							.valueOf(match.getAwayTeamScore())) {
						getTeamFromListById(match.getAwayTeam().getId())
								.getResultData()
								.setPoints(
										getTeamFromListById(
												match.getAwayTeam().getId())
												.getResultData().getPoints() + 3);
						getTeamFromListById(match.getHomeTeam().getId())
								.getResultData().setLoss(
										getTeamFromListById(
												match.getHomeTeam().getId())
												.getResultData().getLoss() + 1);
						getTeamFromListById(match.getAwayTeam().getId())
								.getResultData().setWins(
										getTeamFromListById(
												match.getAwayTeam().getId())
												.getResultData().getWins() + 1);
					}
					if (Integer.valueOf(match.getHomeTeamScore()) == Integer
							.valueOf(match.getAwayTeamScore())) {
						getTeamFromListById(match.getHomeTeam().getId())
								.getResultData()
								.setPoints(
										getTeamFromListById(
												match.getHomeTeam().getId())
												.getResultData().getPoints() + 1);
						getTeamFromListById(match.getAwayTeam().getId())
								.getResultData()
								.setPoints(
										getTeamFromListById(
												match.getAwayTeam().getId())
												.getResultData().getPoints() + 1);
						getTeamFromListById(match.getHomeTeam().getId())
								.getResultData()
								.setDraws(
										getTeamFromListById(
												match.getHomeTeam().getId())
												.getResultData().getDraws() + 1);
						getTeamFromListById(match.getAwayTeam().getId())
								.getResultData()
								.setDraws(
										getTeamFromListById(
												match.getAwayTeam().getId())
												.getResultData().getDraws() + 1);
					}

				}

			}

			Collections.sort(teamList, new HomeGoalsComparator());
			Collections.sort(teamList, new DifferenceComparator());
			Collections.sort(teamList, new PointsComparator());
			for (int i = 0; i < teamList.size(); i++) {
				teamList.get(i).getResultData().setPosition(i + 1);
			}

			exportToFile();
		}

		try {
			FacesContext
					.getCurrentInstance()
					.getExternalContext()
					.redirect(
							"http://www.khfotbal.cz/khfotbal/download?id="
									+ filename);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void exportToFile() {
		BufferedWriter f;
		try {
			f = new BufferedWriter(new FileWriter(FILE_DESTINATION + filename,
					true));

			f.newLine();
			f.newLine();
			f.write(selectedCompetion.getName());
			f.newLine();
			f.write("\n");
			for (Team team : teamList) {
				String teamFrontName = team.getFrontName();
				if (team.getFrontName() == null) {
					teamFrontName = "";
				}

				f.write(Integer.toString(team.getResultData().getPosition()));
				f.write(". ");
				f.write(teamFrontName);
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getMatches()));
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getWins()));
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getDraws()));
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getLoss()));
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getScoredGoals()));
				f.write(":");
				f.write(Integer.toString(team.getResultData()
						.getCollectedGoals()));
				f.write("\t");
				f.write(Integer.toString(team.getResultData().getPoints()));
				f.newLine();
				f.write("\n");
			}

			f.flush();
			f.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public class PointsComparator implements Comparator<Team> {
		public int compare(Team t1, Team t2) {
			return (t2.getResultData().getPoints() - t1.getResultData()
					.getPoints());
		}

	}

	public class DifferenceComparator implements Comparator<Team> {
		public int compare(Team t1, Team t2) {
			return ((t2.getResultData().getScoredGoals() - t2.getResultData()
					.getCollectedGoals()) - (t1.getResultData()
					.getScoredGoals() - t1.getResultData().getCollectedGoals()));
		}

	}

	public class HomeGoalsComparator implements Comparator<Team> {
		public int compare(Team t1, Team t2) {
			return (t2.getResultData().getScoredGoals() - t1.getResultData()
					.getScoredGoals());
		}

	}

}
